<template>
  <div class="learn-container">
    <div class="learn-layout">
      <!-- 左侧课程目录 -->
      <div class="course-sidebar" :class="{ collapsed: sidebarCollapsed }">
        <div class="sidebar-header">
          <div class="course-info">
            <h3>{{ courseInfo.title }}</h3>
            <div class="progress-info">
              <el-progress 
                :percentage="courseProgress" 
                :show-text="false"
                :stroke-width="6"
              />
              <span class="progress-text">{{ completedLessons }}/{{ totalLessons }}</span>
            </div>
          </div>
          <el-button 
            type="text" 
            @click="toggleSidebar"
            class="collapse-btn"
          >
            <el-icon>
              <ArrowLeft v-if="!sidebarCollapsed" />
              <ArrowRight v-else />
            </el-icon>
          </el-button>
        </div>
        
        <div class="chapter-list">
          <div 
            v-for="(chapter, chapterIndex) in chapters"
            :key="chapter.id"
            class="chapter-item"
          >
            <div class="chapter-header" @click="toggleChapter(chapterIndex)">
              <el-icon>
                <CaretRight v-if="!chapter.expanded" />
                <CaretBottom v-else />
              </el-icon>
              <span class="chapter-title">{{ chapter.title }}</span>
            </div>
            
            <div v-show="chapter.expanded" class="lesson-list">
              <div 
                v-for="lesson in chapter.lessons"
                :key="lesson.id"
                class="lesson-item"
                :class="{ 
                  active: currentLesson?.id === lesson.id,
                  completed: lesson.completed,
                  locked: !lesson.canAccess
                }"
                @click="selectLesson(lesson)"
              >
                <div class="lesson-icon">
                  <el-icon v-if="lesson.completed" color="#67c23a">
                    <CircleCheckFilled />
                  </el-icon>
                  <el-icon v-else-if="currentLesson?.id === lesson.id" color="#409eff">
                    <VideoPlay />
                  </el-icon>
                  <el-icon v-else-if="!lesson.canAccess" color="#c0c4cc">
                    <Lock />
                  </el-icon>
                  <el-icon v-else color="#909399">
                    <VideoPlay />
                  </el-icon>
                </div>
                <div class="lesson-info">
                  <div class="lesson-title">{{ lesson.title }}</div>
                  <div class="lesson-duration">{{ formatDuration(lesson.duration) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主要学习区域 -->
      <div class="learn-main">
        <div v-if="!currentLesson" class="no-lesson">
          <el-empty description="请选择要学习的课时" />
        </div>
        
        <div v-else class="lesson-content">
          <!-- 课时头部 -->
          <div class="lesson-header">
            <div class="lesson-info">
              <h2>{{ currentLesson.title }}</h2>
              <div class="lesson-meta">
                <span>时长：{{ formatDuration(currentLesson.duration) }}</span>
                <span>类型：{{ getLessonTypeText(currentLesson.type) }}</span>
              </div>
            </div>
            <div class="lesson-actions">
              <el-button @click="toggleNote" :type="showNote ? 'primary' : 'default'">
                <el-icon><EditPen /></el-icon>
                笔记
              </el-button>
              <el-button @click="toggleFullscreen">
                <el-icon><FullScreen /></el-icon>
                全屏
              </el-button>
            </div>
          </div>

          <!-- 课时主体内容 -->
          <div class="lesson-body">
            <!-- 视频播放器 -->
            <div v-if="currentLesson.type === 'VIDEO'" class="video-player">
              <video
                ref="videoPlayer"
                :src="currentLesson.videoUrl"
                controls
                @timeupdate="onVideoTimeUpdate"
                @ended="onVideoEnded"
                @loadedmetadata="onVideoLoaded"
              >
                您的浏览器不支持视频播放
              </video>
            </div>

            <!-- 文档内容 -->
            <div v-else-if="currentLesson.type === 'DOCUMENT'" class="document-content">
              <div class="document-viewer" v-html="currentLesson.content"></div>
            </div>

            <!-- 音频播放器 -->
            <div v-else-if="currentLesson.type === 'AUDIO'" class="audio-player">
              <audio
                ref="audioPlayer"
                :src="currentLesson.audioUrl"
                controls
                @timeupdate="onAudioTimeUpdate"
                @ended="onAudioEnded"
              >
                您的浏览器不支持音频播放
              </audio>
            </div>

            <!-- 练习题 -->
            <div v-else-if="currentLesson.type === 'EXERCISE'" class="exercise-content">
              <div class="exercise-question">
                <h3>{{ currentLesson.question }}</h3>
                <div class="exercise-options">
                  <el-radio-group v-model="exerciseAnswer">
                    <el-radio 
                      v-for="option in currentLesson.options"
                      :key="option.key"
                      :value="option.key"
                    >
                      {{ option.text }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div class="exercise-actions">
                  <el-button type="primary" @click="submitExercise">提交答案</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 课时底部导航 -->
          <div class="lesson-footer">
            <div class="lesson-nav">
              <el-button 
                @click="previousLesson" 
                :disabled="!hasPreviousLesson"
              >
                <el-icon><ArrowLeft /></el-icon>
                上一课时
              </el-button>
              <el-button 
                type="primary" 
                @click="nextLesson"
                :disabled="!hasNextLesson"
              >
                下一课时
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
            <div class="lesson-complete">
              <el-button 
                v-if="!currentLesson.completed"
                type="success" 
                @click="markAsCompleted"
              >
                标记为已完成
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧笔记面板 -->
      <div v-show="showNote" class="note-panel">
        <div class="note-header">
          <h4>学习笔记</h4>
          <el-button type="text" @click="showNote = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="note-content">
          <el-input
            v-model="noteContent"
            type="textarea"
            :rows="20"
            placeholder="在这里记录学习笔记..."
            @blur="saveNote"
          />
        </div>
        <div class="note-footer">
          <el-button size="small" @click="saveNote">保存笔记</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getCourseDetail,
  getCourseChapters,
  getLessonDetail,
  updateLearningProgress,
  markLessonCompleted,
  saveLessonNote,
  getLessonNote
} from '@/api/classroom'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const sidebarCollapsed = ref(false)
const showNote = ref(false)
const courseInfo = ref({})
const chapters = ref([])
const currentLesson = ref(null)
const noteContent = ref('')
const exerciseAnswer = ref('')
const videoPlayer = ref()
const audioPlayer = ref()

// 计算属性
const totalLessons = computed(() => {
  return chapters.value.reduce((total, chapter) => {
    return total + (chapter.lessons?.length || 0)
  }, 0)
})

const completedLessons = computed(() => {
  return chapters.value.reduce((total, chapter) => {
    return total + (chapter.lessons?.filter(lesson => lesson.completed).length || 0)
  }, 0)
})

const courseProgress = computed(() => {
  if (totalLessons.value === 0) return 0
  return Math.round((completedLessons.value / totalLessons.value) * 100)
})

const hasPreviousLesson = computed(() => {
  return findPreviousLesson() !== null
})

const hasNextLesson = computed(() => {
  return findNextLesson() !== null
})

// 获取课程信息
const loadCourseInfo = async () => {
  try {
    const response = await getCourseDetail(route.params.courseId)
    if (response.code === 200) {
      courseInfo.value = response.data
    }
  } catch (error) {
    console.error('获取课程信息失败:', error)
  }
}

// 获取课程章节
const loadCourseChapters = async () => {
  try {
    const response = await getCourseChapters(route.params.courseId)
    if (response.code === 200) {
      chapters.value = response.data.map(chapter => ({
        ...chapter,
        expanded: true
      }))
      
      // 如果有指定课时ID，自动选择
      if (route.params.lessonId) {
        const lesson = findLessonById(route.params.lessonId)
        if (lesson) {
          selectLesson(lesson)
        }
      }
    }
  } catch (error) {
    console.error('获取课程章节失败:', error)
  }
}

// 查找课时
const findLessonById = (lessonId) => {
  for (const chapter of chapters.value) {
    const lesson = chapter.lessons?.find(l => l.id === lessonId)
    if (lesson) return lesson
  }
  return null
}

// 查找上一课时
const findPreviousLesson = () => {
  if (!currentLesson.value) return null
  
  let found = false
  let previousLesson = null
  
  for (const chapter of chapters.value) {
    for (const lesson of chapter.lessons || []) {
      if (found) return previousLesson
      if (lesson.id === currentLesson.value.id) {
        found = true
        break
      }
      previousLesson = lesson
    }
  }
  return null
}

// 查找下一课时
const findNextLesson = () => {
  if (!currentLesson.value) return null
  
  let found = false
  
  for (const chapter of chapters.value) {
    for (const lesson of chapter.lessons || []) {
      if (found) return lesson
      if (lesson.id === currentLesson.value.id) {
        found = true
      }
    }
  }
  return null
}

// 选择课时
const selectLesson = async (lesson) => {
  if (!lesson.canAccess) {
    ElMessage.warning('请先完成前面的课程')
    return
  }
  
  try {
    const response = await getLessonDetail(lesson.id)
    if (response.code === 200) {
      currentLesson.value = response.data
      await loadLessonNote()
      
      // 更新URL
      router.replace(`/classroom/course/${route.params.courseId}/learn/${lesson.id}`)
    }
  } catch (error) {
    console.error('获取课时详情失败:', error)
    ElMessage.error('获取课时详情失败')
  }
}

// 切换章节展开状态
const toggleChapter = (index) => {
  chapters.value[index].expanded = !chapters.value[index].expanded
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 切换笔记面板
const toggleNote = () => {
  showNote.value = !showNote.value
}

// 全屏
const toggleFullscreen = () => {
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    document.documentElement.requestFullscreen()
  }
}

// 上一课时
const previousLesson = () => {
  const lesson = findPreviousLesson()
  if (lesson) {
    selectLesson(lesson)
  }
}

// 下一课时
const nextLesson = () => {
  const lesson = findNextLesson()
  if (lesson) {
    selectLesson(lesson)
  }
}

// 标记为已完成
const markAsCompleted = async () => {
  try {
    await markLessonCompleted(currentLesson.value.id)
    currentLesson.value.completed = true
    
    // 更新章节中的课时状态
    for (const chapter of chapters.value) {
      const lesson = chapter.lessons?.find(l => l.id === currentLesson.value.id)
      if (lesson) {
        lesson.completed = true
        break
      }
    }
    
    ElMessage.success('已标记为完成')
  } catch (error) {
    console.error('标记完成失败:', error)
    ElMessage.error('标记完成失败')
  }
}

// 视频时间更新
const onVideoTimeUpdate = (event) => {
  const currentTime = event.target.currentTime
  const duration = event.target.duration
  
  // 更新学习进度
  updateProgress(currentTime, duration)
}

// 视频播放结束
const onVideoEnded = () => {
  markAsCompleted()
}

// 视频加载完成
const onVideoLoaded = () => {
  // 恢复播放进度
  if (currentLesson.value.progress && videoPlayer.value) {
    videoPlayer.value.currentTime = currentLesson.value.progress
  }
}

// 音频时间更新
const onAudioTimeUpdate = (event) => {
  const currentTime = event.target.currentTime
  const duration = event.target.duration
  
  updateProgress(currentTime, duration)
}

// 音频播放结束
const onAudioEnded = () => {
  markAsCompleted()
}

// 更新学习进度
const updateProgress = async (currentTime, duration) => {
  if (!currentLesson.value || !duration) return
  
  const progress = Math.round((currentTime / duration) * 100)
  
  try {
    await updateLearningProgress(currentLesson.value.id, {
      currentTime,
      duration,
      progress
    })
  } catch (error) {
    console.error('更新进度失败:', error)
  }
}

// 提交练习答案
const submitExercise = () => {
  if (!exerciseAnswer.value) {
    ElMessage.warning('请选择答案')
    return
  }
  
  const isCorrect = exerciseAnswer.value === currentLesson.value.correctAnswer
  
  if (isCorrect) {
    ElMessage.success('回答正确！')
    markAsCompleted()
  } else {
    ElMessage.error('回答错误，请重试')
  }
}

// 保存笔记
const saveNote = async () => {
  if (!currentLesson.value) return
  
  try {
    await saveLessonNote(currentLesson.value.id, {
      content: noteContent.value
    })
    ElMessage.success('笔记已保存')
  } catch (error) {
    console.error('保存笔记失败:', error)
    ElMessage.error('保存笔记失败')
  }
}

// 加载笔记
const loadLessonNote = async () => {
  if (!currentLesson.value) return
  
  try {
    const response = await getLessonNote(currentLesson.value.id)
    if (response.code === 200) {
      noteContent.value = response.data.content || ''
    }
  } catch (error) {
    console.error('加载笔记失败:', error)
  }
}

// 工具函数
const formatDuration = (minutes) => {
  if (!minutes) return '0分钟'
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  if (hours > 0) {
    return `${hours}小时${mins}分钟`
  }
  return `${mins}分钟`
}

const getLessonTypeText = (type) => {
  const typeMap = {
    'VIDEO': '视频',
    'DOCUMENT': '文档',
    'AUDIO': '音频',
    'EXERCISE': '练习'
  }
  return typeMap[type] || type
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadCourseInfo(),
      loadCourseChapters()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.learn-container {
  height: 100vh;
  overflow: hidden;
}

.learn-layout {
  display: flex;
  height: 100%;
}

.course-sidebar {
  width: 320px;
  background: #f8f9fa;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
  
  &.collapsed {
    width: 0;
    overflow: hidden;
  }
  
  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .course-info {
      flex: 1;
      
      h3 {
        margin: 0 0 8px 0;
        font-size: 16px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .progress-info {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-progress {
          flex: 1;
        }
        
        .progress-text {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
  
  .chapter-list {
    flex: 1;
    overflow-y: auto;
    
    .chapter-item {
      .chapter-header {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 12px 16px;
        cursor: pointer;
        background: #e9ecef;
        border-bottom: 1px solid #dee2e6;
        
        &:hover {
          background: #dee2e6;
        }
        
        .chapter-title {
          font-weight: 600;
          font-size: 14px;
        }
      }
      
      .lesson-list {
        .lesson-item {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 8px 16px 8px 32px;
          cursor: pointer;
          border-bottom: 1px solid #f0f0f0;
          
          &:hover {
            background: #f0f0f0;
          }
          
          &.active {
            background: #e3f2fd;
            border-left: 3px solid #2196f3;
          }
          
          &.completed {
            background: #f1f8e9;
          }
          
          &.locked {
            opacity: 0.5;
            cursor: not-allowed;
          }
          
          .lesson-info {
            flex: 1;
            
            .lesson-title {
              font-size: 13px;
              margin-bottom: 2px;
            }
            
            .lesson-duration {
              font-size: 11px;
              color: #909399;
            }
          }
        }
      }
    }
  }
}

.learn-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .no-lesson {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .lesson-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .lesson-header {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .lesson-info {
        h2 {
          margin: 0 0 8px 0;
          font-size: 20px;
        }
        
        .lesson-meta {
          display: flex;
          gap: 16px;
          color: #909399;
          font-size: 14px;
        }
      }
      
      .lesson-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .lesson-body {
      flex: 1;
      overflow: hidden;
      
      .video-player {
        height: 100%;
        background: #000;
        display: flex;
        align-items: center;
        justify-content: center;
        
        video {
          max-width: 100%;
          max-height: 100%;
        }
      }
      
      .document-content {
        height: 100%;
        overflow-y: auto;
        padding: 20px;
        
        .document-viewer {
          line-height: 1.8;
          font-size: 16px;
        }
      }
      
      .audio-player {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f9fa;
        
        audio {
          width: 80%;
          max-width: 600px;
        }
      }
      
      .exercise-content {
        padding: 20px;
        
        .exercise-question {
          max-width: 800px;
          margin: 0 auto;
          
          h3 {
            margin-bottom: 20px;
          }
          
          .exercise-options {
            margin-bottom: 20px;
            
            .el-radio {
              display: block;
              margin-bottom: 12px;
            }
          }
        }
      }
    }
    
    .lesson-footer {
      padding: 16px 20px;
      border-top: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .lesson-nav {
        display: flex;
        gap: 12px;
      }
    }
  }
}

.note-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  
  .note-header {
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h4 {
      margin: 0;
    }
  }
  
  .note-content {
    flex: 1;
    padding: 16px;
    
    .el-textarea {
      height: 100%;
      
      :deep(.el-textarea__inner) {
        height: 100%;
        resize: none;
      }
    }
  }
  
  .note-footer {
    padding: 16px;
    border-top: 1px solid #ebeef5;
  }
}

@media (max-width: 768px) {
  .course-sidebar {
    width: 280px;
  }
  
  .note-panel {
    width: 250px;
  }
  
  .lesson-header {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 12px;
  }
  
  .lesson-footer {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
